package com.ruoyi.resume.utils.deepseek;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.TimeUnit;

public class DeepSeekV3Client {

    private static final String API_URL = "https://api.deepseek.com/chat/completions"; // DeepSeek API URL
    private static final String API_KEY = "sk-ffcfb6b5398b4b4bbd08a81b900b7d36"; // 替换为你的API密钥

    public static String ds(String message) {
        // 构建请求体
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 构建消息
            String requestBody = objectMapper.writeValueAsString(new DeepSeekRequest(
                    "deepseek-chat",
                    new Message[]{
                            new Message("system", "You are a helpful assistant"),
                            new Message("user", message)
                    },
                    false
            ));

            // 创建URL对象
            URL url = new URL(API_URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为POST
            connection.setRequestMethod("POST");

            // 设置请求头
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Authorization", "Bearer " + API_KEY);

            // 设置超时时间
            connection.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(30));
            connection.setReadTimeout((int) TimeUnit.SECONDS.toMillis(60));

            // 允许写入数据
            connection.setDoOutput(true);

            // 发送请求体
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = requestBody.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            // 获取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"))) {
                    StringBuilder response = new StringBuilder();
                    String responseLine;
                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }
                    String responseBody = response.toString();
                    System.out.println("Response: " + responseBody);

                    return extractMessageContent(responseBody);
                }
            } else {
                System.err.println("Request failed: " + responseCode + " - " + connection.getResponseMessage());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    // 定义请求体结构
    static class DeepSeekRequest {
        private String model;
        private Message[] messages;
        private boolean stream;

        public DeepSeekRequest(String model, Message[] messages, boolean stream) {
            this.model = model;
            this.messages = messages;
            this.stream = stream;
        }

        public String getModel() {
            return model;
        }

        public Message[] getMessages() {
            return messages;
        }

        public boolean isStream() {
            return stream;
        }
    }

    // 定义消息结构
    static class Message {
        private String role;
        private String content;

        public Message(String role, String content) {
            this.role = role;
            this.content = content;
        }

        public String getRole() {
            return role;
        }

        public String getContent() {
            return content;
        }
    }

    private static String extractMessageContent(String responseJson) {
        // 解析响应JSON
        JSONObject responseObject = JSON.parseObject(responseJson);

        //获取"choices" -> "message" -> "content" 字段的值
        JSONObject choices = responseObject.getJSONArray("choices").getJSONObject(0);
        if (choices != null) {
            JSONObject message = choices.getJSONObject("message");
            if (message != null) {
                return message.getString("content"); // 提取并返回 "content" 字段
            }
        }

        // 如果没有找到内容，返回一个空字符串
        return "";
    }
}